<template>
    <div class="dashboard-editor-container">
        <div class="main-header">
            <el-row style="background: #fff; padding: 16px 16px;">
                <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"/>
                <div>
                    <!-- <el-button size="small" type="primary" @click="dialogClick(1)">新增</el-button> -->
                    <!-- <el-button size="small" type="primary">导入</el-button>
                    <el-button size="small" type="primary">导出</el-button> -->
                    <!-- <el-button size="small" type="danger" :disabled="disabled" @click="handleDelete(1)">删除选中</el-button> -->
                </div>
                <el-table border @selection-change="handleSelectionChange" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" :data="tableData" style="width: 100%;margin-top:20px;" >
                    <!-- <el-table-column type="selection" width="55"></el-table-column> -->
                    <el-table-column type="index" label="序号" width="50"></el-table-column>
                    <el-table-column prop="Type" :formatter="typeFormat" width="130" label="审计类型"></el-table-column>
                    <!-- <el-table-column prop="CmdCode" label="编码" width="130"></el-table-column> -->
                    <el-table-column prop="Descp" label="操作命令">
                        <template slot-scope="scope">
                            {{ scope.row.Descp+'('+scope.row.CmdCode+')' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="Enabled" width="130" label="审计生效">
                        <template slot-scope="scope">
                            <span v-if="scope.row.Enabled === 0" style="color:#909399">否</span>
                            <span v-if="scope.row.Enabled === 1" style="color:#67C23A">是</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Level" width="130" label="严重等级">
                        <template slot-scope="scope">
                            <p style="color:red" v-if="scope.row.Level === 1">致命</p>
                            <p style="color:#F56C6C" v-if="scope.row.Level === 2">紧急</p>
                            <p style="color:#E6A23C" v-if="scope.row.Level === 3">重要</p>
                            <p style="color:#E6A23C" v-if="scope.row.Level === 4">监视</p>
                            <p style="color:#409EFF" v-if="scope.row.Level === 5">普通</p>
                            <p style="color:#67C23A" v-if="scope.row.Level === 6">通知</p>
                        </template>
                    </el-table-column>
                    <el-table-column width="180" label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" @click="dialogClick(2,scope.row)" title="编辑" icon="el-icon-edit" circle></el-button>
                            <!-- <el-button size="mini" @click="handleDelete(2,scope.row)" title="删除" type="danger" icon="el-icon-delete" circle></el-button> -->
                        </template>
                    </el-table-column>
                    <template slot="empty">
                        <div class="empty">
                            <svg-icon icon-class="notAvailable" class="notAvailable"></svg-icon>
                            <span>{{imgTitle}}</span>
                        </div>  
                    </template>
                </el-table>
                <el-pagination @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page=pageNum
          :page-size=pageSize
          background
          layout="total, prev, pager, sizes, next, jumper"
          :total="total"></el-pagination>
                
                <el-dialog v-el-drag-dialog title='编辑审计策略' :visible.sync="centerDialogVisible" top='7%'  width="40%" @close='closeDialog' :close-on-press-escape = false  :close-on-click-modal = false >
                    <!-- <span>这是一个dialog</span> -->
                    <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="30%">
                        <!-- <el-card shadow="never" class="border-none margin-t24"> -->
                            <el-row :gutter="24">
                                <el-col :sm="24" :md="24" :lg="24">
                                    <el-form-item  label="审计类型：" prop="Type">
                                        <!-- <el-input size="small" style="width:70%;" v-model="ruleForm.Type" disabled ></el-input>  -->
                                        <el-select size="small" style="width:100%" placeholder="请选择审计类型" v-model="ruleForm.Type">
                                            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"/>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :sm="24" :md="24" :lg="24">
                                    <el-form-item  label="操作命令：" prop="Descp">
                                        <el-input  size="small" style="width:70%;" v-model="ruleForm.Descp" ></el-input> 
                                    </el-form-item>    
                                </el-col>

                                <el-col :sm="24" :md="24" :lg="24">
                                    <el-form-item  label="审计生效：" prop="Enabled">
                                        <el-select size="small" v-model="ruleForm.Enabled" placeholder="请选择应用层协议" style="width:100%;">
                                            <el-option :value="0" label="否"/>
                                            <el-option :value="1" label="是"/>
                                        </el-select>
                                    </el-form-item>    
                                </el-col>

                                <el-col :sm="24" :md="24" :lg="24">
                                    <el-form-item  label="严重等级：" prop="Level">
                                        <!-- <el-input size="small" style="width:70%;" v-model="ruleForm.Type" disabled ></el-input>  -->
                                        <el-select size="small" style="width:100%" placeholder="请选择审计类型" v-model="ruleForm.Level">
                                            <el-option v-for="item in LevelList" :key="item.value" :label="item.label" :value="item.value"/>
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <!-- <el-col :sm="24" :md="24" :lg="24">
                                    <el-form-item  label="描述" prop="Describe">
                                        <el-input maxlength='100' show-word-limit type="textarea" size="small" v-model="ruleForm.Describe" :rows="3" placeholder="请输入描述"></el-input>  
                                    </el-form-item>
                                </el-col> -->
                            </el-row>
                        <!-- </el-card> -->
                    </el-form>    
                    <span slot="footer" class="dialog-footer"> 
                        <el-button v-if="this.showTitle === 1" size="small" class="newadd" type="primary" @click="determineClick('ruleForm',1)">确定</el-button>
                        <el-button v-if="this.showTitle === 2" size="small" class="newadd" type="primary" @click="determineClick('ruleForm',2)">保存</el-button>
                        <el-button  size="small" class="newadd"  @click="cancelClick()">取消</el-button>
                    </span>
                </el-dialog>
                 </el-row>   
            </div>
        
    </div>        
</template>

<script>
// import { GetProtocol } from '@/utils/publicMethod';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { connrequest } from "@/api/firstPage.js"
import connsearch from "../logAnalysis/components/connsearch.vue";
// import { GetCollectRule, DelCollectRule, AddCollectRule, EditCollectRule, GetCustomProtocolList, } from '@/api/operator';
export default {
    components: { connsearch },
    directives:{
        elDragDialog
    },
    data(){
        let _that = this
        var validators = (rule,value,callback) =>{
            var regIPd = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\/(\d{1,2})$/;
            var regIP = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/;
            var prefixIP = /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))([1-2][0-9]|3[0-2]|[1-9])$/;
            var decimalnetmask = /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))((254|252|248|240|224|192|128|0)\.0\.0\.0|(255\.(254|252|248|240|224|192|128|0)\.0\.0)|(255\.255\.(254|252|248|240|224|192|128|0)\.0)|(255\.255\.255\.(254|252|248|240|224|192|128|0)))$/;
            var lasIP = /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))-(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))$/;
            if (regIP.test(value)||prefixIP.test(value)||decimalnetmask.test(value)||lasIP.test(value)||regIPd.test(value)||value==='all') {
                callback()
            } else if(value === '' || value === undefined){
                callback(new Error('地址不能为空'))
            } else {
                callback(new Error('请输入正确的IP地址/网段格式'))
            }
            // var regIP = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/
            // if (regIP.test(value)) {
            //     callback()
            // } else if(value === '' || value === undefined || value === 'all'){
            //     callback()
            // } else {
            //     callback(new Error('请输入正确的IP地址格式'))
            // }
        };
        return{
            tableData:[],
            imgTitle:'数据加载中，请稍后......',
            formOptions: [
                {
                    col: 8,
                    hidden: false,
                    label: "严重性等级", // label文字
                    prop: "Level", // 字段名
                    element: "el-select", // 指定elementui组件
                    initValue: 0, // 字段初始值,
                    placeholder: "请选择严重性等级", // elementui组件属性
                    name:'AuditLogLevel',
                    options: [],
                    rules: [], // elementui组件属性
                    events: {
                        // elementui组件方法
                        input(val) {
                        // console.log(val)
                        }
                    }
                },
                {
                    col: 8,
                    label: "审计类型",
                    prop: "Type",
                    element: "el-select",
                    name:'AuditLogType',
                    initValue: 0,
                    options: [],
                    events:{
                        input (val) {
                            _that.getAuditFilterInfo(val);
                            _that.$refs.connsearch.searchform.CmdCode = 0;
                        }
                    }
                    },
                    {
                    col: 8,
                    label: "操作命令",
                    prop: "CmdCode",
                    element: "el-select",
                    initValue: 0,
                    options: [],
                    events:{
                        input (val) {
                        // this.getAuditFilterInfo(val);
                        // console.log(val);
                        }
                    }
                    }
            ],
            ruleForm:{
                Type:0,
                Enabled:1,
                CmdCode:0,
                Descp:'',
                Level:0
            },
            rules:{
                SrcIP:[
                    {required: true, validator:validators, trigger:"blur" }
                ],
                DstIP:[
                    { required: true, validator:validators, trigger:"blur" }
                ],
                NTLP:[
                    { required: true, message:'请选择传输层协议', trigger:"change" }
                ],
                SPDY:[
                    { required: true, message:'请选择应用层协议', trigger:"change" }
                ]
            },
            searchFrom:{},
            ProtocolList: [{label:'全部',value:'all'}],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            showTitle:1,
            Dictionaries:{},
            disabled:true,
            arrayList:[], //装取selection选中数据
            typeList:[],
            LevelList:[],
            jurisdiction:false,
            centerDialogVisible:false
        }
    },
    created(){
        this.GetUIDictParam('')
        this.$set(this.searchFrom,'Level', 0)
        this.$set(this.searchFrom,'Type', 0)
        this.$set(this.searchFrom,'CmdCode', 0)
        this.getData();
        this.getAuditFilterInfo(0)
        
        // this.GetCustomProtocolList();
        // GetProtocol().then(res => { this.ProtocolList = res });
    },
    mounted(){
        
    },
    watch:{
        centerDialogVisible(val){
            if (!val) {
                this.$refs['ruleForm'].resetFields();
            }
        },
        // 监听批量批量删除是否可点击
        arrayList(val){
            if (val.length === 0) {
                this.disabled = true;
            }else{
                this.disabled = false;
            }
        }
    },
    methods:{
        async GetUIDictParam(type){
            const data = {
                Data : {
                    FilterType:type
                }
            }
            const res = await connrequest('GetUIDictParam',data)
            if (type === '') {
                this.Dictionaries = res.Data;
                this.formOptions.map( item => {
                    item.options = [{value: 0, label: '全部'}]
                    for (const key in res.Data) {
                        if(item.name === key){
                            res.Data[key].map(items=>{
                                item.options.push({
                                    label:items.Descp,
                                    value:items.Value
                                })
                            })
                        }
                    }
                })
            } else {
                
            }
            
        },
        async getData(){
            const data = {
                Filter : this.searchFrom,
                Paging: {
                    QueryPageNo: this.pageNum,
                    QueryPageLength: this.pageSize
                }
            };
            const res = await connrequest('GetParamDictSysCmd',data);
            this.tableData = res.Data;
            this.total = res.Paging.TotalCount
        },
        // // 获取审计类型下拉框数据
        // async getAuditTypeList(){
        //     const res = await connrequest('GetAuditTypeList')
        //     let arr = [{value: 0, label: '全部'}]
        //     this.formOptions.map( item => {
        //         if(item.label === '审计事件'){
        //         item.options = [...arr,...res.Data.Type]
        //         }
        //     })
        // },
        // async GetUIDictParam(){
        //     let levelOption = []
        //     let typeOption = []
        //     const res = await connrequest('GetUIDictParam')
        //     this.Dictionaries = res.Data;
        //     let arr = [{value: 0, label: '全部'}]
        //     res.Data.AuditLogLevel.map(levelItem=>{
        //         levelOption.push({
        //             label:levelItem.Descp,
        //             value:levelItem.Value
        //         })
        //         this.LevelList.push({
        //             label:levelItem.Descp,
        //             value:levelItem.Value
        //         })
        //     })
        //     res.Data.AuditLogType.map(logTypeItem=>{
        //         typeOption.push({
        //             label:logTypeItem.Descp,
        //             value:logTypeItem.Value
        //         })
        //         this.typeList.push({
        //             label:logTypeItem.Descp,
        //             value:logTypeItem.Value
        //         })
        //     })
        //     this.formOptions.map( item => {
        //         if(item.label === '严重性等级'){
        //             item.options = [...arr,...levelOption]
        //         }else if(item.label === '审计类型'){
        //             item.options = [...arr,...typeOption]
        //         }
        //     })
        // },
        typeFormat(row){
            let type = ''
            this.Dictionaries.AuditLogType.map(item=>{
                if (row.Type===item.Value) {
                    type = item.Descp
                }
            })
            return type
        },
        
        async getAuditFilterInfo(type){
            const data={
                Data:{
                    Type:type
                }
            }
            const res = await connrequest('GetAuditFilterInfo',data)
            res.Data = res.Data.CmdCode.map(item => {
                item.label = item.Descp
                item.value = item.CmdCode
                return item
            })
            let arr = [{value: 0, label: '全部'}]
            this.formOptions.map( item => {
                if(item.label === '操作命令'){
                    item.options = [...arr,...res.Data]
                }
                // console.log(this.$refs.connsearch.addInitValue());
            })
            
        },
        async GetCustomProtocolList(){
            const paramData = {
                Header:{
                    CmdCode:'GetCustomProtocolList'
                },
                Token:this.$store.state.user.Token
            }
            const res = await GetCustomProtocolList(paramData);
            if (res.Status.StatusCode===0) {
                res.Data.forEach(item => {
                    this.ProtocolList.push({label:item,value:item})
                })
            }
        },
        handleSelectionChange(val){
            this.arrayList = []; 
            val.forEach(item => {
                this.arrayList.push(item.ID);
            });
        },
        closeDialog() {
            // 重置表单
            this.$nextTick(() => {
                // this.ruleForm = Object.assign({}, );
                this.$refs['ruleForm'].clearValidate();
                this.$refs['ruleForm'].resetFields();
            });
        },
        cancelClick(){
            this.centerDialogVisible = false;
            this.$nextTick(() => {
                this.$refs['ruleForm'].resetFields();
            });
        },
        determineClick(formName,status){
            this.$refs[formName].validate(async(valid) => {
                if (valid) {
                    if (status === 1) {
                        // console.log(111111111);
                        this.AddCollectRule(); 
                    } else {
                        this.EditCollectRule();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });  
        },
        async AddCollectRule(){
            const paramData = { 
                Header:{
                    CmdCode:"AddCollectRule"
                },
                Data: this.ruleForm,
                Token:this.$store.state.user.Token
            }
            const res = await AddCollectRule(paramData);
            if (res.Status.StatusCode===0) {
                this.getData();
                this.$message.success("操作成功");
                this.centerDialogVisible = false;
            }
        },
        async EditCollectRule(){
            const data = { 
                Data:this.ruleForm
                // Header:{
                //     CmdCode:"ModifyParamDictSysCmd"
                // },
                // Data: this.ruleForm,
                // Token:this.$store.state.user.Token
                
            }
            const res = await connrequest('ModifyParamDictSysCmd',data)
            // const res = await EditCollectRule(paramData);
            if (res.Status.StatusCode===0) {
                // this.getData = res.Data;
                this.getData();
                this.$message.success("操作成功");
                this.centerDialogVisible = false;
            }
        },
        dialogClick(status,row){
            this.centerDialogVisible = true;
            if (status===1) {
                this.showTitle = 1;
            }else if(status === 2){
                this.showTitle = 2;
                this.ruleForm = {...row};
            }
        },
        handleCurrentChange(pageNum){
            this.pageNum = pageNum;
            this.getData()
        },
        // 条数
        handleSizeChange(pageSize){
            this.pageNum = 1;
            this.pageSize = pageSize;
            this.getData()
        },
        // 删除
        // 删除
        async handleDelete(status,row){
            if (status===1) {
                var ID = this.arrayList;
            }else{
                var ID = [];
                ID.push(row.ID)
            }
            const paramData = {
                Header: {
                    CmdCode: "DelCollectRule"
                },
                Data:ID,
                Token:this.$store.state.user.Token
            }
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                const res = await DelCollectRule(paramData);
                if (res.Status.StatusCode===0) {
                    this.getData();
                }
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        search(val){
            this.searchFrom = {...val};
            this.getData();
        },
        reset(){
            this.$set(this.searchform,'CmdCode', 0)
            this.$set(this.searchform,'Level', 0)
            this.$set(this.searchform,'Type', 0)
            this.getData()
        }
    }
}
</script>

<style lang='scss' scoped>
.el-select{
    width: 70% !important;
}
.el-textarea{
    width: 70% !important;
}

</style>